import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

import Login from '@/views/login'
import index from '@/views/index'
import zhuce from '@/views/zhuce'
import person from "@/views/person";
import commodity from "@/views/commodity";
import productClassify from "@/views/productClassify"
import rpwd from "@/views/rpwd"
import cart from "@/views/cart";

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta:{
      isLogin:false
    }
  },
  {
    path: '/index',
    name: 'index',
    component: index,
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    meta:{
      isLogin:false
    }
  },
  {
    path: '/zhuce',
    name: 'zhuce',
    component: zhuce,
    meta:{
      isLogin:false
    }
  },
  {
    path: '/person',
    name: 'person',
    component: person,
    meta: {
      isLogin: true
    }
  },
  {
    path: '/commodity/:id',
    name: 'commodity',
    component: commodity,
    meta:{
      isLogin:false
    }
  },
  {
    path: '/productClassify',
    name: 'productClassify',
    component: productClassify,
    meta: {
      isLogin: false
    }
    
    },
  {
    path: '/rpwd',
    name: 'rpwd',
    component: rpwd,
    meta: {
      isLogin: false
    }
    },
  {
    path: '/cart',
    name: 'cart',
    component: cart,
    meta:{
      isLogin:true
    }
  }
  
]

const router = new VueRouter({
  routes
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push  = function push (location){
  return originalPush.call(this,location).catch(err =>err)
}
const originaReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location){
  return originaReplace.call(this,location).catch(err =>err)
}
router.beforeEach((to,from,next) => {

  //判断需要跳转到目标界面是否需要登陆
  const isLogin = to.meta.isLogin
  //目标界面需要登陆
  if(isLogin == true){
    //判断有是否已经登陆
    //获取登陆状态
    const token = Vue.prototype.$cookies.get("token")
    //如果令牌存在
    if (token){
      next()
    }else {
      next("/login")

    }
  }else{
    //从原界面跳转到目标界面
    next()
  }
})

export default router
